package fi.hell.lunchit.testing

import fi.hell.lunchit.*
import fi.hell.enums.*
import org.codehaus.groovy.grails.commons.ApplicationHolder
import org.springframework.mock.web.MockServletContext

class DomainFactory {
	static int i = 0
	
	static getUser(Map newValues = [:]) {
		
		Map values = [
		    "email":"no-reply${i++}@invaliddomainname.aa",
		    "firstName":"Jukka",
		    "lastName":"Hell",
		    "password":"716668d2decae9d71ab597bc25584c0f921c04e7", //  = sha1generatedpassword
		    "rounds":[]
		]
		
		setNewValues(values, newValues)
		
		return new User(values)
	}
	
	static getRestaurant(Map newValues = [:]) {
		
		byte[] logo = getMockRestaurantLogo()

		Map values = [
		    "name":"Burgerplace${i++}",
		    "distance":100,
		    "logo":logo,
		    "homePage":"http://www.homepageforburgerplace.com",
		    "openingDays":[Day.MONDAY, Day.TUESDAY],
			"tags":[]
		]
		
		setNewValues(values, newValues)
		
		return new Restaurant(values)
	}
	
	static byte[] getMockRestaurantLogo() {
		String imageName = "mockupRestaurantLogo.png"
		MockServletContext ctx = ApplicationHolder.application.mainContext.servletContext
		String path = ctx.getRealPath("/")
		File file = new File(path + "/WEB-INF/testing/"+imageName)

		assert file.exists()

		try {
			byte[] bytes = fileToByteArray(file)
			return bytes
		} catch(IOException ioe) {
			println "IOException occurred: ${ioe.getMessage()}"
			return new byte[0]
		}
	}
	
	static byte[] fileToByteArray(File file) throws IOException {
		InputStream is = new FileInputStream(file);
	    
        // Get the size of the file
        long length = file.length()
    
        if (length > Integer.MAX_VALUE) {
            return new byte[0]
        }
    
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length]
    
        // Read in the bytes
        int offset = 0
        int numRead = 0
        while (offset < bytes.length
               && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead
        }
    
        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName())
        }
    
        // Close the input stream and return bytes
        is.close()
        
        return bytes
	}
	
	/**
	 * Replace old values with new if there is something
	 */
	static void setNewValues(Map currentValues, Map newValues) {
		
		// Domains won't have that much attributes that we can't use each 
		newValues.each { key, value ->
			currentValues.key = value
		}
	}
	
	static Calendar getRoundDay(int year, int month, int day) {
		Calendar c = Calendar.getInstance()
		c.set(year, month, day, 0, 0, 0) 
		return c
	}
}